package best.driver.android.Listener;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import best.driver.android.Utils.Logger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VerifycodeReceiver extends ContentObserver {

    public interface VerifycodeListener {
        public void onReceiveVerifycode(String verifycode);
    }

    private Context mContext;
    private Cursor cursor = null;
    private VerifycodeListener listener;

    public VerifycodeReceiver(Context context, Handler handler) {
        super(handler);
        mContext = context;
    }

    public void setListener(VerifycodeListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean deliverSelfNotifications() {
        return true;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

        Uri inBoxUri = Uri.parse("content://sms/");
        cursor = mContext.getContentResolver().query(inBoxUri, null, null, null, "date desc");
        if (cursor != null) {
            StringBuffer sb = new StringBuffer();
            while (cursor.moveToNext()) {
                sb.append(cursor.getString(cursor.getColumnIndex("body")));
                if (!TextUtils.isEmpty(sb.toString())) {
                    break;
                }
            }
            cursor.close();
            String content = sb.toString();
            Logger.d("USER", "sms:" + content);

            if (isEDJSms(sb.toString())) {

                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(content);

                while(m.find()) {
                    int len = m.end() - m.start();
                    if (len == 4) {
                        if (listener != null) {
                            listener.onReceiveVerifycode(content.substring(m.start(), m.end()));
                        }
                        break;
                    }
                }
            }
        }
    }

    public static boolean isEDJSms(String sms) {
        sms = sms.trim();
        Pattern p = Pattern.compile("百世物流");
        Matcher m = p.matcher(sms);
        return m.find();
    }

}
